package 剑指offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _32从上到下打印二叉树2 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();//返回层序序列

        if(root == null){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> temp = new ArrayList<>();
            //保证了层
            for (int i = queue.size(); i > 0; i--) {
                TreeNode father = queue.poll();
                temp.add(father.val);
                if (father.left != null){
                    queue.offer(father.left);
                }
                if (father.right != null){
                    queue.offer(father.right);
                }
            }
            result.add(temp);
        }
        return result;
    }
}
